import { useEffect, useState } from 'react';

// React 18+ 的新特性，确保在 effect 中使用的事件处理函数不会被闭包捕获   18.2引入  实验性功能
// import { experimental_useEffectEvent as useEffectEvent } from 'react'; 

export function useFadeIn(ref, duration) {
  const [isRunning, setIsRunning] = useState(true);

  useAnimationLoop(isRunning, (timePassed) => {
    const progress = Math.min(timePassed / duration, 1);
    ref.current.style.opacity = progress;
    if (progress === 1) {
      setIsRunning(false);
    }
  });
}

// 设置动画循环的逻辑从 useFadeIn 提取到自定义 Hook useAnimationLoop：
function useAnimationLoop(isRunning, drawFrame) {
  // const onFrame = useEffectEvent(drawFrame);

  useEffect(() => {
    if (!isRunning) {
      return;
    }

    const startTime = performance.now();
    let frameId = null;

    function tick(now) {
      const timePassed = now - startTime;
      drawFrame(timePassed);
      // onFrame(timePassed);
      frameId = requestAnimationFrame(tick);
    }

    tick();
    return () => cancelAnimationFrame(frameId);
  }, [isRunning, drawFrame]); // 依赖项中添加 drawFrame 确保在其变化时重新运行 effect
}

